package com.ermace.robo.jumper;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ermace.robo.jumper.game.GameObjects.Bitmaps;
import com.ermace.robo.jumper.game.Player.RobotColour;

public class DifficultyActivity extends Activity {

	private Intent intent;
	
	private static int totalNumberAI;
	private int maxNumber = 5;
	private static int easyAI = 1;
	private static int mediumAI = 0;
	private static int hardAI = 0;
	
	private boolean backPressed = false;
	
	public static int getEasyAI() { //TODO wegdoen en meegeven aan intent ma geen idee hoe ge da doe :p
		return easyAI;
	}

	public static int getMediumAI() { //TODO wegdoen en meegeven aan intent ma geen idee hoe ge da doe :p
		return mediumAI;
	}
	
	public static int getHardAI() { //TODO wegdoen en meegeven aan intent ma geen idee hoe ge da doe :p
		return hardAI;
	}
	
	private final static List<RobotColour> easyColourList = new ArrayList<RobotColour>();
	private final static List<RobotColour> mediumColourList = new ArrayList<RobotColour>();
	private final static List<RobotColour> hardColourList = new ArrayList<RobotColour>();

	/**
	 * @return the easycolorlist
	 */
	public static List<RobotColour> getEasyColourList() {
		return new ArrayList<RobotColour>(easyColourList);
	}

	/**
	 * @return the mediumcolourlist
	 */
	public static List<RobotColour> getMediumColourList() {
		return new ArrayList<RobotColour>(mediumColourList);
	}

	/**
	 * @return the hardcolourlist
	 */
	public static List<RobotColour> getHardColourList() {
		return new ArrayList<RobotColour>(hardColourList);
	}

	private TextView currentAI;
	private TextView maxAI;

	private LinearLayout easyColourLayout;
	private LinearLayout mediumColourLayout;
	private LinearLayout hardColourLayout;
	
	private final List<RobotColour> availableColours = new ArrayList<RobotColour>();
	private Bitmap desaturatedSprite;
	private Bitmap normal;
	private int spriteIndex = 1;

	private ImageView easyMin;
	private ImageView easyPlus;
	private ImageView mediumMin;
	private ImageView mediumPlus;
	private ImageView hardPlus;
	private ImageView hardMin;
	
	private Button startButton;
	
	private Bundle b;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        //Remove title bar
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);

        //Remove notification bar
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        
        setContentView(R.layout.difficulty);
        intent = new Intent(this, MapSelectionActivity.class);
        
        desaturatedSprite = BitmapFactory.decodeResource(getResources(), R.drawable.robot_front_desaturated);
        desaturatedSprite = Bitmap.createScaledBitmap(desaturatedSprite, 3*desaturatedSprite.getWidth() / 5, 3 * desaturatedSprite.getHeight() / 5, true);
        
        if( Bitmaps.getInstance().getBitmap(R.drawable.spritesheet) != null)
        	normal = Bitmaps.getInstance().getBitmap(R.drawable.spritesheet);
        else
        	normal = BitmapFactory.decodeResource(getResources(), R.drawable.spritesheet);
        normal = Bitmap.createBitmap(normal, 0, 0, normal.getWidth(), normal.getHeight() / 10);
        normal = Bitmap.createScaledBitmap(normal, 3*normal.getWidth() / 5, 3*normal.getHeight() / 5, true);
        
        easyColourLayout = (LinearLayout) findViewById(R.id.easyColours);
        mediumColourLayout = (LinearLayout) findViewById(R.id.mediumColours);
        hardColourLayout = (LinearLayout) findViewById(R.id.hardColours);
        
        startButton = (Button)findViewById(R.id.startButton);
        startButton.setOnTouchListener(startButtonListener);
        
        easyMin = (ImageView) findViewById(R.id.easyMin);
        easyPlus = (ImageView) findViewById(R.id.easyPlus);
        mediumMin = (ImageView) findViewById(R.id.mediumMin);
        mediumPlus = (ImageView) findViewById(R.id.mediumPlus);
        hardMin = (ImageView) findViewById(R.id.hardMin);
        hardPlus = (ImageView) findViewById(R.id.hardPlus);
       
        for(RobotColour colour: RobotColour.values())
        	availableColours.add(colour);
        
        b = new Bundle();
        
        initializeColourButtons();
		//updateTextView();
		updateButtons();
    }

	/**
	 * 
	 */
	private void initializeColourButtons() {

		Bitmap background = generateButtonBitmap(null);
		
		for (int i = 0; i < 5; i++) {
			ImageButton easyButton = (ImageButton) easyColourLayout.getChildAt(i);
			easyButton.setImageBitmap(background);
			easyButton.setEnabled(false);
			easyButton.setClickable(false);
			
			ImageButton mediumButton = (ImageButton) mediumColourLayout.getChildAt(i);
			mediumButton.setImageBitmap(background);
			mediumButton.setEnabled(false);
			mediumButton.setClickable(false);
			
			ImageButton hardButton = (ImageButton) hardColourLayout.getChildAt(i);
			hardButton.setImageBitmap(background);
			hardButton.setEnabled(false);
			hardButton.setClickable(false);
		}
		
		availableColours.remove(RobotColour.NONE);

		int i = 0;
		for (RobotColour colour: easyColourList) {
			enableColourSelector(easyColourLayout, colour, ++i);
			availableColours.remove(colour);
		}
		i = 0;
		for (RobotColour colour: mediumColourList) {
			enableColourSelector(mediumColourLayout, colour, ++i);
			availableColours.remove(colour);
		}
		i = 0;
		for (RobotColour colour: hardColourList) {
			enableColourSelector(hardColourLayout, colour, ++i);
			availableColours.remove(colour);
		}
		
		//	for the initial case
		if (easyAI == 1 && easyColourList.isEmpty()) {
			RobotColour colour = getNextRobotColour();
			easyColourList.add(colour);
			enableColourSelector(easyColourLayout, colour, 1);
		}
	}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        //getMenuInflater().inflate(R.menu.menu1, menu);
        return true;
    }
    
    private OnTouchListener plusListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			ImageView iv = (ImageView) v;
			iv.setImageResource(R.drawable.square_button_light_plus);
			
			switch(event.getAction()) {
//				case MotionEvent.ACTION_HOVER_EXIT:
//					iv.setImageResource(R.drawable.square_button_plus);
//					break;
					
				case MotionEvent.ACTION_OUTSIDE:
					iv.setImageResource(R.drawable.square_button_plus);
					break;
					
				case MotionEvent.ACTION_UP:
					iv.setImageResource(R.drawable.square_button_plus);
					updateText((String) v.getTag());
			}
			
			return true;
		}
	};
	
	 private OnTouchListener minListener = new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				
				ImageView iv = (ImageView) v;
				iv.setImageResource(R.drawable.square_button_light_min);
				
				switch(event.getAction()) {
//					case MotionEvent.ACTION_HOVER_EXIT:
//						iv.setImageResource(R.drawable.square_button_min);
//						break;
						
					case MotionEvent.ACTION_OUTSIDE:
						iv.setImageResource(R.drawable.square_button_min);
						break;
						
					case MotionEvent.ACTION_UP:
						iv.setImageResource(R.drawable.square_button_min);
						updateText((String) v.getTag());
				}
				
				return true;
			}
		};
    
  
    
    private void updateText(String toUpdate)
    {
    	if(totalNumberAI < maxNumber)
    	{
    		
    		if(toUpdate.equals("easyPlus")) {
    			easyAI += 1;
    			easyColourList.add(enableColourSelector(easyColourLayout, easyAI));
    		}
    		if(toUpdate.equals("mediumPlus")) {
    			mediumAI += 1;
    			mediumColourList.add(enableColourSelector(mediumColourLayout, mediumAI));
    		}
    		if(toUpdate.equals("hardPlus")) {
    			hardAI += 1;
    			hardColourList.add(enableColourSelector(hardColourLayout, hardAI));
    		}
    	}
    	if(totalNumberAI > 0)
    	{
    		if(toUpdate.equals("hardMin")) {
      			hardColourList.remove(disableColourSelector(hardColourLayout, hardAI--));
    		}
    		if(toUpdate.equals("mediumMin")) {
      			mediumColourList.remove(disableColourSelector(mediumColourLayout, mediumAI--));
    		}
    		if(toUpdate.equals("easyMin")) {
      			easyColourList.remove(disableColourSelector(easyColourLayout, easyAI--));
    		}
    	}
    	//updateTextView();
		totalNumberAI = easyAI + mediumAI + hardAI;
    	updateButtons();
    }

	/**
	 * @return
	 */
	private RobotColour getNextRobotColour() {
		RobotColour nextColour;
		if (availableColours.size() > 1)
    		nextColour = availableColours.remove(0);
    	else
    		nextColour = availableColours.get(0);
		return nextColour;
	}
    
    /**
     * 
     * @param	parent
     * 			The layout to add the colour to.
     * @param	number
     * 			The number of the selector.
     * 
     * @return	The colour of the robot added to the layout.
     */
    private RobotColour enableColourSelector(LinearLayout parent, int number) {
    	
    	RobotColour currentColour;
    	currentColour = getNextRobotColour();
    	
    	enableColourSelector(parent, currentColour, number);
    	
    	return currentColour;
    }
    
    /**
     * 
     * @param parent
     * @param colour
     * @param	number
     * 			The number of the selector.
     * 
     * @note	Does not remove the colour from the available colours list.
     */
    private void enableColourSelector(LinearLayout parent, RobotColour robotColour, int number) {
    	
    	ImageButton button = (ImageButton) parent.getChildAt(number - 1);
    	button.setEnabled(true);

    	button.setImageBitmap(generateButtonBitmap(robotColour));
    	button.setId(robotColour.ordinal());
    }
    
    /**
     *  
     * @param	parent
     * 			The layout to remove the colour from.
     * @param	number
     * 			The number of the selector.
     * 
     * @return	The colour of the robot removed from the layout.
     */
    private RobotColour disableColourSelector(LinearLayout parent, int number) {
    	ImageButton selector = (ImageButton) parent.getChildAt(number - 1);
    	RobotColour toDelete = RobotColour.getByOrdinal(selector.getId());
    	if (! availableColours.contains(toDelete))
    		availableColours.add(toDelete);
    	
    	selector.setImageBitmap(generateButtonBitmap(null));
    	selector.setEnabled(false);
    	
    	return toDelete;
    }

	/**
	 * @param robotColour
	 */
	private Bitmap generateButtonBitmap(RobotColour robotColour) {
		Bitmap standard = Bitmap.createBitmap(desaturatedSprite, 0, 0, spriteIndex * desaturatedSprite.getWidth() / 9, desaturatedSprite.getHeight());
		
		if (robotColour == null)
			return standard;
		
		standard = Bitmap.createBitmap(normal, 0, 0, spriteIndex * normal.getWidth() / 9, normal.getHeight());
			
		Bitmap overlay = robotColour.getSpriteSheet(getResources());
		overlay = Bitmap.createBitmap(overlay, 0, 0, spriteIndex * overlay.getWidth() / 9, overlay.getHeight() / 9);
    	overlay = Bitmap.createScaledBitmap(overlay, standard.getWidth(), standard.getHeight(), true);
    	
    	Bitmap combined = Bitmap.createBitmap(standard.getWidth(), standard.getHeight(), Config.ARGB_8888);
    	Canvas combiner = new Canvas(combined);
    	
    	Drawable drawable1 = new BitmapDrawable(getResources(), standard);
        Drawable drawable2 = new BitmapDrawable(getResources(), overlay);

        drawable1.setBounds(0, 0, standard.getWidth(), standard.getHeight());
        drawable1.draw(combiner);
        
        drawable2.setBounds(0, 0, combiner.getWidth(), combiner.getHeight());
        drawable2.draw(combiner);
        
        return combined;
	}

    private OnTouchListener startButtonListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			
			startButton.setBackgroundResource(R.drawable.choosemap_button_pressed);
			
			switch(event.getAction()) {
				case MotionEvent.ACTION_OUTSIDE:
					startButton.setBackgroundResource(R.drawable.choosemap_button);
					break;
					
				case MotionEvent.ACTION_UP:
					startButton.setBackgroundResource(R.drawable.choosemap_button);
					MainActivity.startingNewActivity = true;
					startActivity(intent);
					return true;
			}
			
			return true;
		}
	};


	private void updateButtons() {
		if(totalNumberAI == 5)
		{
			easyPlus.setImageResource(R.drawable.square_button_plus_disabled);
			easyPlus.setOnTouchListener(null);
			mediumPlus.setImageResource(R.drawable.square_button_plus_disabled);
			mediumPlus.setOnTouchListener(null);
			hardPlus.setImageResource(R.drawable.square_button_plus_disabled);
			hardPlus.setOnTouchListener(null);
		}
		else
		{
			easyPlus.setOnTouchListener(plusListener);
			mediumPlus.setOnTouchListener(plusListener);
			hardPlus.setOnTouchListener(plusListener);
			easyPlus.setImageResource(R.drawable.square_button_plus);
			mediumPlus.setImageResource(R.drawable.square_button_plus);
			hardPlus.setImageResource(R.drawable.square_button_plus);
		}
		
		if(easyAI == 0)
		{
			easyMin.setImageResource(R.drawable.square_button_min_disabled);
			easyMin.setOnTouchListener(null);
		}
		else{
			easyMin.setImageResource(R.drawable.square_button_min);
	        easyMin.setOnTouchListener(minListener);
		}
		if(mediumAI == 0)
		{
			mediumMin.setImageResource(R.drawable.square_button_min_disabled);
			mediumMin.setOnTouchListener(null);
			
		}else{
			mediumMin.setImageResource(R.drawable.square_button_min);
			mediumMin.setOnTouchListener(minListener);
		}
		if(hardAI == 0)
		{
			hardMin.setImageResource(R.drawable.square_button_min_disabled);
			hardMin.setOnTouchListener(null);
		}
		else{
			hardMin.setImageResource(R.drawable.square_button_min);
			hardMin.setOnTouchListener(minListener);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
			MainActivity.resumeMusic();
	}
	
	@Override
	protected void onPause() {
		super.onPause();
			if(!backPressed )
				MainActivity.pauseMusic();
	}
	
	@Override
	public void onBackPressed() {
		backPressed = true;
		super.onBackPressed();
	}
	
}
